/**
 * HTTP请求封装工具
 * 创建时间：2025-09-11
 * 作者：开发团队
 * 目的：封装axios请求，统一处理认证、错误等
 */

import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
import type { ApiResponse } from '@/types/common'
import { useAuthStore } from '@/stores/auth'
import { showError, showWarning } from '@/utils/message'

// 创建axios实例
const request: AxiosInstance = axios.create({
  baseURL: '/api/v1',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 添加认证token
    const authStore = useAuthStore()
    if (authStore.token) {
      config.headers.Authorization = `Bearer ${authStore.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  ((response: AxiosResponse<ApiResponse<any>>) => {
    // 对于所有API，统一处理响应格式
    console.log('API响应:', response);
    const { code, message, data, error } = response.data;
    
    // 业务成功
    if (code === 200) {
      console.log('API响应数据:', data);
      return data; // 只返回data字段，而不是整个response.data
    }
    
    // 业务失败
    const errorMessage = message || error || '请求失败';
    showError(errorMessage);
    return Promise.reject(new Error(errorMessage));
  }) as (value: AxiosResponse<ApiResponse<any>>) => any | Promise<any>,
  (error) => {
    // HTTP错误处理
    if (error.response) {
      const { status, data } = error.response;
      
      switch (status) {
        case 401:
          // 未授权，清除token并跳转登录
          const authStore = useAuthStore();
          authStore.logout();
          showError('登录已过期，请重新登录');
          break;
        case 403:
          showError('权限不足');
          break;
        case 404:
          showError('请求的资源不存在');
          break;
        case 500:
          showError('服务器内部错误');
          break;
        default:
          showError(data?.message || data?.error || '请求失败');
      }
    } else if (error.request) {
      showError('网络连接失败');
    } else {
      showError('请求配置错误');
    }
    
    return Promise.reject(error);
  }
)

// 请求方法封装
export const httpRequest = {
  get<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return request.get(url, config)
  },
  
  post<T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {
    return request.post(url, data, config)
  },
  
  put<T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {
    return request.put(url, data, config)
  },
  
  delete<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return request.delete(url, config)
  },
  
  // 文件上传
  upload<T = unknown>(url: string, file: File, config?: AxiosRequestConfig): Promise<T> {
    const formData = new FormData()
    formData.append('file', file)
    
    return request.post(url, formData, {
      ...config,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 文件下载
  download(url: string, filename?: string, config?: AxiosRequestConfig): Promise<void> {
    return request.get(url, {
      ...config,
      responseType: 'blob'
    }).then((response) => {
      const blob = new Blob([response.data])
      const downloadUrl = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = filename || 'download'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(downloadUrl)
    })
  }
}

export default request